package org.base.common.aspect;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Slf4j
public class PerformanceAspect {

    /**
     * 大于该配置时间打印警告异常
     */
    public static final int SECONDS = 1;

    @Pointcut("execution(* org.base.*..controller..*.*(..))")
    public void performancePointcut() {
    }

    @Around("performancePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Class<?> declaringClass = method.getDeclaringClass();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object proceed = joinPoint.proceed();
        stopWatch.stop();
        long time = stopWatch.getTime(TimeUnit.MILLISECONDS);
        String methodFullName = declaringClass.getName() + "." + method.getName();
        if (time / 1000 > SECONDS) {
            log.warn("方法 {} 执行时间 {} ms", methodFullName, time);
        } else {
            log.debug("方法 {} 执行时间 {} ms", methodFullName, time);
        }
        return proceed;
    }
}
